package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Resource
    private IFollowService followService;

    @Override
    public Result likeBlog(Long id) {
        //更改使用scoreSet，用分数进行排行，然后按顺序返回点赞用户头像
        Long userId = UserHolder.getUser().getId();
        //判断是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        if (score ==null){
            //1.如果没点赞，点赞数+1，增加集合
            boolean like = update().setSql("liked = liked+1").eq("id", id).update();
            if (BooleanUtil.isTrue(like)){
                stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY+id,userId.toString(),System.currentTimeMillis());
            }
        }else {
            //2.如果已经点赞，则取消点赞-1，并删除集合
            boolean ifLike = update().setSql("liked = liked-1").eq("id", id).update();
            if (BooleanUtil.isTrue(ifLike)){
                stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY+id,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        List<UserDTO> userDTOS;
        //将top5的用户返回
        //1.在Redis中利用文章id，查询top5点赞用户id
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if (top5 ==null ||top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.根据用户id查询user
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        //3.将user封装成userDto
        //注意：这里的listByIds底层是使用in,查询出来的结果默认按照id递增排序，这里我们需要按照时间升序排序，需要注入sql实现！
        if (ids.size() >1){
            userDTOS = userService
                    .query().in("id",ids).last("ORDER BY FIELD("+idStr+")").list()
                    .stream()
                    .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                    .collect(Collectors.toList());
        }else {
            userDTOS = userService.listByIds(ids).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                    .collect(Collectors.toList());
        }
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("新增文章失败！");
        }
        //1.查询所有粉丝 select * from tb_follow where follow_user_id = userId
        List<Follow> fans = followService.query().eq("follow_user_id", userId).list();
        List<Long> fansId = fans.stream().map(follow -> follow.getUserId()).collect(Collectors.toList());
        //2.将文章id推送到用户邮箱(实质就是将文章id保存到粉丝的Redis中SortedSet集合中)
        for (Long fanId : fansId){
            String key = "mail:" + fanId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryFollowBlog(Long max, Integer offset) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.查询邮件箱
        String key = "mail:" + userId;
        Set<ZSetOperations.TypedTuple<String>> blogSet =
                stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.非空判断
        if (blogSet == null || blogSet.isEmpty()){
            return Result.ok();
        }
        long minTime = 0;
        int os = 1;
        List<Long> ids = new ArrayList<>(blogSet.size());
        for (ZSetOperations.TypedTuple<String> blogTuple : blogSet){
            ids.add(Long.valueOf(blogTuple.getValue()));
            long time = blogTuple.getScore().longValue();
            if (time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id",ids).last("ORDER BY FIELD(id,"+idStr+")").list();
        for (Blog blog : blogs){
            isBlogLiked(blog);
        }
        ScrollResult scrollResult = new ScrollResult(blogs,minTime,os);
        return Result.ok(scrollResult);
    }
    public void isBlogLiked(Blog blog){
        UserDTO user = UserHolder.getUser();
        if (user ==null){
            return;
        }
        Long userId = user.getId();
        Double isLike = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());
        blog.setIsLike(isLike !=null);
    }
}
